package org.ciallo.simplemusicplayer.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import com.bumptech.glide.Glide;
import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.slider.Slider;
import org.ciallo.simplemusicplayer.R;
import org.ciallo.simplemusicplayer.data.model.Song;
import org.ciallo.simplemusicplayer.dialog.PlayQueueDialogFragment;
import org.ciallo.simplemusicplayer.dialog.PlayerSongDetailsDialogFragment;
import org.ciallo.simplemusicplayer.dialog.SongOptionsDialogFragment;
import org.ciallo.simplemusicplayer.service.MediaPlayerService;
import org.ciallo.simplemusicplayer.util.Constants;
import org.ciallo.simplemusicplayer.util.TimeUtil;
import org.ciallo.simplemusicplayer.viewmodel.SharedViewModel;
import timber.log.Timber;

import static org.ciallo.simplemusicplayer.util.SongMetadataUtil.getEmbeddedPicture;

/**
 * @author Jukomu
 * @Description: 全屏音乐播放器界面。
 * 显示当前播放歌曲的详细信息、专辑封面、播放进度和控制按钮。
 * 通过 PlayerController 与 MediaPlayerService 交互来控制播放和接收状态更新。
 * @Package: org.ciallo.simplemusicplayer.activity
 * @Project: SimpleMusicPlayer
 * @name: PlayerActivity
 * @Date: 2025/5/27-02:15
 * @Filename: PlayerActivity
 */
public class PlayerActivity extends AppCompatActivity {
    // --- UI 控件 ---
    private MaterialToolbar toolbar;
    private TextView toolbarTitleTextView; // Toolbar中间的标题
    private ImageView ivAlbumArt;          // 专辑封面
    private TextView tvSongTitleMarquee;   // 歌曲标题（跑马灯效果）
    private TextView tvArtistName;         // 歌手名
    private Slider sliderProgress;         // 播放进度条
    private TextView tvCurrentTime;        // 当前播放时间
    private TextView tvTotalTime;          // 歌曲总时长
    private ImageButton btnPlayMode;       // 播放模式按钮
    private ImageButton btnPrevious;       // 上一首按钮
    private FloatingActionButton fabPlayPause; // 播放/暂停浮动操作按钮
    private ImageButton btnNext;           // 下一首按钮
    private ImageButton btnMoreOptions;    // 更多操作按钮 ("...")
    private ImageButton btnShare;          // 分享按钮 (Toolbar右侧)
    private ImageButton btnPlaylistQueue; // 对播放列表按钮的引用

    // --- 控制器和状态 ---
    private SharedViewModel sharedViewModel; // SharedViewModel 引用
    private Song currentSongForUI;              // 当前在UI上显示的歌曲对象，主要用于分享等操作
    private Song songCurrentlyDisplayedInStaticUI = null; // 用于跟踪静态UI显示的歌曲
    private boolean isUserSeeking = false;         // 标记用户是否正在拖动进度条
    private int lastKnownPlayMode = -1; // 用于比较播放模式是否发生变化

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player);
        // 初始化 ViewModel <--- 确保这一行存在并且没有被注释掉
        sharedViewModel = new ViewModelProvider(this).get(SharedViewModel.class);

        // 初始化UI控件
        toolbar = findViewById(R.id.toolbar_player_top);
        toolbarTitleTextView = findViewById(R.id.toolbar_title_player);
        ivAlbumArt = findViewById(R.id.imageView_player_album_art);
        tvSongTitleMarquee = findViewById(R.id.textView_player_song_title);
        tvArtistName = findViewById(R.id.textView_player_artist_name);
        sliderProgress = findViewById(R.id.slider_player_progress);
        tvCurrentTime = findViewById(R.id.textView_player_current_time);
        tvTotalTime = findViewById(R.id.textView_player_total_time);
        btnPlayMode = findViewById(R.id.button_player_play_mode);
        btnPrevious = findViewById(R.id.button_player_previous);
        fabPlayPause = findViewById(R.id.fab_player_play_pause);
        btnNext = findViewById(R.id.button_player_next);
        btnPlaylistQueue = findViewById(R.id.button_player_playlist_queue);
        btnMoreOptions = findViewById(R.id.button_player_more_options);
        btnShare = findViewById(R.id.button_share_song);

        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowTitleEnabled(false);
        }
        // AndroidManifest中设置了parentActivityName，系统会自动处理返回
        toolbar.setNavigationOnClickListener(v -> onBackPressed()); // 或者使用 onBackPressed()

        // 设置UI控件的监听器 (保持不变)
        setupListeners();

        // 观察 SharedViewModel 暴露的 LiveData
        observePlaybackInfoFromViewModel();
    }

    /**
     * 更新界面上显示的静态歌曲信息（Toolbar标题、主内容区标题、艺术家、封面）。
     * 这个方法应该只在歌曲实际改变时被调用。
     *
     * @param song 要显示的歌曲对象。
     */
    /**
     * 更新静态UI元素：Toolbar标题、主内容区歌曲名、主内容区艺术家名、专辑封面。
     * 这个方法只应该在歌曲对象本身发生变化时被调用。
     */
    private void updateStaticUIElements(@Nullable Song song) {
        String previousSongTitle = (songCurrentlyDisplayedInStaticUI != null) ? songCurrentlyDisplayedInStaticUI.getTitle() : "null";
        String newSongTitle = (song != null) ? song.getTitle() : "null";
        Timber.i("PlayerActivity_StaticUI: Update called. Previous song: '%s', New song: '%s'", previousSongTitle, newSongTitle);
        currentSongForUI = song; // 用于分享等
        songCurrentlyDisplayedInStaticUI = song; // 更新当前静态UI跟踪的歌曲

        if (song == null) {
            // 主内容区
            tvSongTitleMarquee.setText(getString(R.string.no_song_playing));
            tvArtistName.setText("");
            // Toolbar 标题
            toolbarTitleTextView.setText(getString(R.string.app_name));
            toolbarTitleTextView.setSelected(false);
            // 专辑封面
            ivAlbumArt.setImageResource(R.drawable.default_album_art);
        } else {
            // 主内容区
            tvSongTitleMarquee.setText(song.getTitle());
            tvArtistName.setText(song.getArtistName());
            // Toolbar 标题
            String toolbarTitleText = song.getTitle();
            if (song.getArtistName() != null && !song.getArtistName().isEmpty() &&
                    !Constants.UNKNOWN_STRING.equalsIgnoreCase(song.getArtistName())) {
                toolbarTitleText += " - " + song.getArtistName();
            }
            toolbarTitleTextView.setText(toolbarTitleText);

            // 专辑封面 (Glide 加载逻辑不变)
            String artUriString = song.getAlbumArtUri();
            if (artUriString != null && !artUriString.isEmpty()) {
                Glide.with(this).load(Uri.parse(artUriString))
                        .placeholder(R.drawable.default_album_art).error(R.drawable.default_album_art).into(ivAlbumArt);
            } else {
                Bitmap embeddedCover = getEmbeddedPicture(song.getPath());
                if (embeddedCover != null) ivAlbumArt.setImageBitmap(embeddedCover);
                else ivAlbumArt.setImageResource(R.drawable.default_album_art);
            }
        }
    }

    /**
     * 更新动态UI元素：播放/暂停按钮、进度条、当前时间、总时长、播放模式图标。
     * 这个方法可以在每次播放状态或进度更新时被调用。
     */
    private void updateDynamicUIElements(@NonNull MediaPlayerService.PlaybackInfo playbackInfo) {
        Timber.v("PlayerActivity_DynamicUI: Update called. Playing: %b, Pos: %d, Dur: %d, Mode: %d",
                playbackInfo.isPlaying, playbackInfo.currentPositionMs, playbackInfo.durationMs, playbackInfo.playMode);

        // 播放/暂停按钮
        fabPlayPause.setImageResource(playbackInfo.isPlaying ? R.drawable.ic_pause_large : R.drawable.ic_play_arrow_large);

        // 进度条和时间
        long duration = playbackInfo.durationMs;
        if (duration <= 0 && playbackInfo.song != null && playbackInfo.song.getDuration() > 0) {
            duration = playbackInfo.song.getDuration();
        }
        if (duration <= 0) duration = 100; // Default to avoid issues

        tvTotalTime.setText(TimeUtil.formatDuration(duration));
        sliderProgress.setValueTo(duration);

        if (!isUserSeeking) {
            long currentPosition = playbackInfo.currentPositionMs;
            if (currentPosition > duration && duration > 0) currentPosition = duration;
            sliderProgress.setValue(currentPosition);
            tvCurrentTime.setText(TimeUtil.formatDuration(currentPosition));
        }

        // 播放模式图标和Toast
        boolean playModeActuallyChanged = (lastKnownPlayMode != -1 && lastKnownPlayMode != playbackInfo.playMode);
        updatePlayModeButtonIcon(playbackInfo.playMode, playModeActuallyChanged);
        lastKnownPlayMode = playbackInfo.playMode;
    }


    /**
     * 设置播放控制按钮和进度条的监听器。
     */
    private void setupListeners() {
        fabPlayPause.setOnClickListener(v -> sharedViewModel.togglePlayPause()); // 通过 SharedViewModel 调用
        btnPrevious.setOnClickListener(v -> sharedViewModel.playPrevious());   // 通过 SharedViewModel 调用
        btnNext.setOnClickListener(v -> sharedViewModel.playNext());         // 通过 SharedViewModel 调用
        btnPlayMode.setOnClickListener(v -> sharedViewModel.cyclePlayMode()); // 通过 SharedViewModel 调用

        btnPlayMode.setOnClickListener(v -> {
            if (sharedViewModel != null) {
                // 获取当前播放模式，以便在模式改变后显示正确的 Toast
                MediaPlayerService.PlaybackInfo currentInfo = sharedViewModel.playbackInfo.getValue();
                int currentModeBeforeCycle = (currentInfo != null) ? currentInfo.playMode : Constants.PLAY_MODE_ORDER;

                sharedViewModel.cyclePlayMode(); // 请求切换模式

                // 推断下一个模式并显示 Toast
                // 注意：这里是基于 cyclePlayMode 的逻辑 (current + 1) % COUNT
                // 真正的模式更新会通过 LiveData 回调到 observePlaybackInfoFromViewModel -> updatePlayModeButtonIcon
                // Toast 应该在 LiveData 更新后再显示，以确保显示的是实际切换后的模式。
                // 但是，如果 cyclePlayMode 内部不直接返回新模式，我们只能在这里预测。

                // 一个更好的方式是在 observePlaybackInfoFromViewModel 中处理 Toast，
                // 只有当 playMode 发生变化时才显示。
            }
        });

        btnPlaylistQueue.setOnClickListener(v -> {
            PlayQueueDialogFragment.newInstance().show(getSupportFragmentManager(), PlayQueueDialogFragment.TAG);
        });

        btnMoreOptions.setOnClickListener(this::showMoreOptionsMenu);
        btnShare.setOnClickListener(v -> shareCurrentSong());

        sliderProgress.addOnChangeListener((slider, value, fromUser) -> {
            if (fromUser) {
                tvCurrentTime.setText(TimeUtil.formatDuration((long) value));
            }
        });
        sliderProgress.addOnSliderTouchListener(new Slider.OnSliderTouchListener() {
            @Override
            public void onStartTrackingTouch(@NonNull Slider slider) {
                isUserSeeking = true;
            }

            @Override
            public void onStopTrackingTouch(@NonNull Slider slider) {
                isUserSeeking = false;
                sharedViewModel.seekTo((long) slider.getValue()); // 通过 SharedViewModel 调用
            }
        });
    }

    /**
     * 观察 SharedViewModel 中的 playbackInfo LiveData 来更新UI。
     */
    private void observePlaybackInfoFromViewModel() {
        MediaPlayerService.playbackInfo.observe(this, playbackInfo -> {
            long entryTime = System.nanoTime(); // 记录进入观察者的时间
            Timber.d("PlayerActivity_Observer: Received PlaybackInfo update. Song: %s, Playing: %b, Pos: %d",
                    (playbackInfo != null && playbackInfo.song != null ? playbackInfo.song.getTitle() : "null"),
                    (playbackInfo != null ? playbackInfo.isPlaying : false),
                    (playbackInfo != null ? playbackInfo.currentPositionMs : -1));

            if (playbackInfo == null) {
                if (songCurrentlyDisplayedInStaticUI != null) { // 只有当之前有歌，现在没了才更新静态UI
                    Timber.d("PlayerActivity_Observer: playbackInfo is null, was displaying a song. Updating static UI to null.");
                    updateStaticUIElements(null);
                }
                lastKnownPlayMode = Constants.PLAY_MODE_ORDER;
                // 手动设置动态UI到停止状态
                fabPlayPause.setImageResource(R.drawable.ic_play_arrow_large);
                sliderProgress.setValue(0);
                sliderProgress.setValueTo(100);
                tvCurrentTime.setText(TimeUtil.formatDuration(0));
                tvTotalTime.setText(TimeUtil.formatDuration(0));
                updatePlayModeButtonIcon(Constants.PLAY_MODE_ORDER, false);

                // 处理 Toolbar 标题的跑马灯
                if (toolbarTitleTextView.isSelected()) {
                    toolbarTitleTextView.setSelected(false);
                    Timber.d("PlayerActivity_Marquee: toolbarTitleTextView.setSelected(false) (playbackInfo null)");
                }

                if (playbackInfo != null && playbackInfo.errorMessage != null && !playbackInfo.errorMessage.isEmpty()) {
                    Toast.makeText(this, "错误: " + playbackInfo.errorMessage, Toast.LENGTH_LONG).show();
                }
                return;
            }

            // 1. 检查歌曲对象是否真的发生了变化
            boolean songObjectChanged = false;
            if (playbackInfo.song == null && songCurrentlyDisplayedInStaticUI != null) {
                songObjectChanged = true;
            } else if (playbackInfo.song != null && songCurrentlyDisplayedInStaticUI == null) {
                songObjectChanged = true;
            } else if (playbackInfo.song != null && songCurrentlyDisplayedInStaticUI != null) {
                if (!playbackInfo.song.equals(songCurrentlyDisplayedInStaticUI)) {
                    songObjectChanged = true;
                }
            }
            Timber.v("PlayerActivity_Observer: songObjectChanged: %b", songObjectChanged);

            // 2. 如果歌曲对象变了，才更新静态UI部分
            if (songObjectChanged) {
                updateStaticUIElements(playbackInfo.song);
            }
            currentSongForUI = playbackInfo.song;

            // 3. 总是更新动态UI部分
            updateDynamicUIElements(playbackInfo);

            // 4. 专门处理跑马灯的激活状态
            boolean shouldMarqueeBeActive = (playbackInfo.song != null && playbackInfo.isPlaying);
            if (toolbarTitleTextView.isSelected() != shouldMarqueeBeActive) {
                toolbarTitleTextView.setSelected(shouldMarqueeBeActive);
                Timber.d("PlayerActivity_Marquee: toolbarTitleTextView.setSelected(%b)", shouldMarqueeBeActive);
            }

            // 5. 处理错误信息 (不变)
            if (playbackInfo.errorMessage != null && !playbackInfo.errorMessage.isEmpty()) {
                Toast.makeText(this, "播放器错误: " + playbackInfo.errorMessage, Toast.LENGTH_LONG).show();
            }
            long exitTime = System.nanoTime();
            Timber.v("PlayerActivity_Observer: Processing took %d ns.", (exitTime - entryTime));
        });
    }

    /**
     * 显示包含歌曲详细信息和更多操作的底部弹出对话框。
     *
     * @param anchorView 触发此操作的视图（通常是“更多操作”按钮）。
     */
    private void showMoreOptionsMenu(View anchorView) { // anchorView 参数现在可能不需要了，因为是BottomSheet
        if (currentSongForUI == null && sharedViewModel == null) {
            Toast.makeText(this, "当前无歌曲或播放服务不可用", Toast.LENGTH_SHORT).show();
            return;
        }
        SongOptionsDialogFragment.newInstance(currentSongForUI.getId())
                .show(getSupportFragmentManager(), SongOptionsDialogFragment.TAG);
    }

    /**
     * 分享当前正在播放的歌曲信息。
     */
    private void shareCurrentSong() {
        if (currentSongForUI != null) { // 使用UI上当前显示的歌曲信息
            Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setType("text/plain");
            String shareBody = "我正在听: " + currentSongForUI.getTitle();
            if (currentSongForUI.getArtistName() != null && !currentSongForUI.getArtistName().isEmpty() && !currentSongForUI.getArtistName().equalsIgnoreCase("未知歌手")) {
                shareBody += " - " + currentSongForUI.getArtistName();
            }
            // 如果有歌曲的在线链接或应用内链接，可以加入
            // shareIntent.putExtra(Intent.EXTRA_SUBJECT, "分享歌曲：" + currentSongForUI.getTitle());
            shareIntent.putExtra(Intent.EXTRA_TEXT, shareBody);
            startActivity(Intent.createChooser(shareIntent, "分享到..."));
        } else {
            Toast.makeText(this, "当前没有可分享的歌曲", Toast.LENGTH_SHORT).show();
        }
    }

    // --- 生命周期和权限处理 ---
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 由 SharedViewModel 的 onCleared() 处理
        Timber.d("PlayerActivity onDestroy");
    }


    /**
     * 根据当前的播放模式更新播放模式按钮的图标。
     *
     * @param playMode           当前的播放模式。
     * @param showToastIfChanged 如果模式发生变化，是否显示Toast提示。
     */
    private void updatePlayModeButtonIcon(int playMode, boolean showToastIfChanged) { // 添加新参数
        int iconRes;
        String contentDescription = ""; // 初始化
        switch (playMode) {
            case Constants.PLAY_MODE_SHUFFLE:
                iconRes = R.drawable.ic_play_mode_shuffle;
                contentDescription = getString(R.string.play_mode_shuffle_description); // 使用 strings.xml
                break;
            case Constants.PLAY_MODE_SINGLE_LOOP:
                iconRes = R.drawable.ic_play_mode_single_loop;
                contentDescription = getString(R.string.play_mode_single_loop_description);
                break;
            case Constants.PLAY_MODE_LIST_LOOP:
                iconRes = R.drawable.ic_play_mode_list_loop;
                contentDescription = getString(R.string.play_mode_list_loop_description);
                break;
            case Constants.PLAY_MODE_ORDER:
            default:
                iconRes = R.drawable.ic_play_mode_order;
                contentDescription = getString(R.string.play_mode_order_description);
                break;
        }

        btnPlayMode.setImageResource(iconRes);
        btnPlayMode.setContentDescription(contentDescription);

        // 只有当模式实际发生变化时才显示 Toast
        if (showToastIfChanged) {
            Timber.d("PlayerActivity_PlayMode: Mode changed to '%s', showing Toast.", contentDescription);
            Toast.makeText(this, contentDescription, Toast.LENGTH_SHORT).show();
        }
    }

}
